package com.itheima.reggie.ctrl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.model.dto.DishDto;
import com.itheima.reggie.model.dto.SetmealDto;
import com.itheima.reggie.model.entity.*;
import com.itheima.reggie.service.CategoryService;
import com.itheima.reggie.service.SetmealDishService;
import com.itheima.reggie.service.SetmealService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Slf4j
@RestController
@RequestMapping("/setmeal")
public class SetmealController {

    @Autowired
    private SetmealService setmealService;

    @Autowired
    private SetmealDishService setmealDishService;

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 新增套餐
     *
     * @param setmealDto
     * @return
     */
    @PostMapping
    @CacheEvict(value = "setmealCache",allEntries = true) //清理setmealCache分类下所有缓存数据
    public R<java.lang.String> save(@RequestBody SetmealDto setmealDto){
        log.info("接收到新增套餐数据,setmealDto={}",setmealDto.toString());

        setmealService.savaWithDish(setmealDto);

        return R.success("新增套餐成功");
    }

    /**
     * 套餐分页查询
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @GetMapping("/page")
    public R<Page> page(Integer page, Integer pageSize, String name){
        //分页构造器
        Page<Setmeal> pageInfo = new Page<>(page,pageSize);
        Page<SetmealDto> dtoPage = new Page<>();

        //条件构造器
        LambdaQueryWrapper<Setmeal> wrapper = new LambdaQueryWrapper<>();
        //添加查找条件
        wrapper.like(StringUtils.isNotBlank(name),Setmeal::getName,name);
        //添加排序条件
        wrapper.orderByDesc(Setmeal::getUpdateTime);

        //执行分页查询，查询返回的数据自动保存到pageInfo中
        setmealService.page(pageInfo,wrapper);

        //对象拷贝，pageInfo 拷贝到setmealDtoPage
        BeanUtils.copyProperties(pageInfo,dtoPage,"records"); //因为pageInfo,dtoPage的records泛型不一样，所以拷贝的时候得忽略

        //得到Setmeal（pageInfo）分页查询返回的记录
        List<Setmeal> records = pageInfo.getRecords();
        //设置SetmealDto（dtoPage）的records
        List<SetmealDto> list = records.stream().map((item) -> {//每个item都是一个setmeal对象
            SetmealDto setmealDto = new SetmealDto();
            BeanUtils.copyProperties(item, setmealDto);//因为new出来的，全为空所以需要将item中属性拷贝到setmealDto来
            //根据套餐分类id找到套餐分类name
            Category category = categoryService.getById(item.getCategoryId());//先通过setmeal中的categoryId找到category
            if (category != null) {
                setmealDto.setCategoryName(category.getName());//在从该category中取出name，赋给setmealDto中的categoryName
            }
            return setmealDto;
        }).collect(Collectors.toList());

        dtoPage.setRecords(list);
        return R.success(dtoPage);
    }

    /**
     * 根据id删除套餐
     * @param ids
     * @return
     */
    @DeleteMapping
    @Transactional
    @CacheEvict(value = "setmealCache",allEntries = true) //清理setmealCache分类下所有缓存数据
    public R<String> delete(@RequestParam List<Long> ids){
        log.info("要删除的套餐id为:{}",ids);

        setmealService.removeWithDish(ids);

        return R.success("套餐数据删除成功");
    }

    //http://localhost:8090/setmeal/status/0?ids=1724328539832045570
    //如status/0 则需要 @PostMapping("/status/{status}")， 参数那里用用@PathVariable Integer status
    //?ids=1724328539832045570 这种情况用@RequestParam
    @PostMapping("/status/{status}")
    public R<String> updateStatus(@PathVariable Integer status,@RequestParam List<Long> ids){
        log.info("setmeal:{}",ids);

        //由ids得到setmeals
        List<Setmeal> setmeals = setmealService.listByIds(ids);

        //遍历每个setmeals，将其status赋为传入的status
        setmeals.stream().map((item) -> {//每一个item就是一个Dish实体
            //将每个dish的status设置为传入参数status
            item.setStatus(status);
            //更新每个dish
            setmealService.updateById(item);
            return item;
        }).collect(Collectors.toList());

        return R.success("修改成功");
    }


    /**
     * 根据条件查询套餐数据
     * @param setmeal
     * @return
     */
    @GetMapping("/list")
    @Cacheable(value = "setmealCache",key = "#setmeal.categoryId + '_' + #setmeal.status")
    public R<List<SetmealDto>> list(Setmeal setmeal){

        //1根据传入的参数查到该分类对应的套餐list。
        LambdaQueryWrapper<Setmeal> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(setmeal.getCategoryId() != null,Setmeal::getCategoryId,setmeal.getCategoryId());
        wrapper.eq(setmeal.getStatus() != null,Setmeal::getStatus,setmeal.getStatus());
        wrapper.orderByDesc(Setmeal::getUpdateTime);
        List<Setmeal> setmeals = setmealService.list(wrapper);

        //遍历setmeals,生成setmealDtos
        List<SetmealDto> setmealDtoList = setmeals.stream().map((item) -> {
            SetmealDto setmealDto = new SetmealDto();
            BeanUtils.copyProperties(item, setmealDto);

            LambdaQueryWrapper<SetmealDish> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(SetmealDish::getSetmealId, item.getId());
            List<SetmealDish> setmealDishes = setmealDishService.list(queryWrapper);
            setmealDto.setSetmealDishes(setmealDishes);
            return setmealDto;
        }).collect(Collectors.toList());
        return R.success(setmealDtoList);
    }

}
